package com.minivision.fdiot.mqtt.serialize.msgpack;

import java.io.IOException;

import org.msgpack.MessageTypeException;
import org.msgpack.packer.Packer;
import org.msgpack.template.AbstractTemplate;
import org.msgpack.unpacker.Unpacker;

/**
 * msgpack java pojo对象处理模板
 * @author hughzhao
 * @2018年3月2日
 * @param <T>
 */
public class PojoTemplate<T> extends AbstractTemplate<T> {
  
  private Class<T> clazz;
  
  public PojoTemplate(Class<T> clazz) {
    this.clazz = clazz;
  }

  @Override
  public void write(Packer pk, T v, boolean required) throws IOException {
    if (v == null) {
      if (required) {
        throw new MessageTypeException("Attempted to write null");
      }
      pk.writeNil();
      return;
    }
    pk.write(v);
  }

  @Override
  public T read(Unpacker u, T to, boolean required) throws IOException {
    if (!required && u.trySkipNil()) {
      return null;
    }
    return u.read(clazz);
  }

}
